package com.bodacn.keypoint;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import androidx.fragment.app.Fragment;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**points
 * A simple {@link Fragment} subclass.
 */
public class FragmentG extends Fragment implements View.OnClickListener {
    public static final int msgFocusBarcode = 1001;
    public static final int MSG_SCANBARCODE = 1002;
    public static final int MSG_MEASURE=1003;
    public static final int MSG_FocusDefaultItem=1004;
    public static final int MSG_SUBMIT=1005;
    public static final int msgGetImg=1006;
    ReentrantLock reentrantLock = new ReentrantLock();
    public static String TAG=FragmentG.class.getName();
    //用于将Activity中的参数传给Fragment
    private Map<String, Object> fragmentParams = new HashMap<String, Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    //全局变量
    Toast curToast;
    String curLoginUserNo, curLoginUser, curServiceUrl = "",curServiceDir="",curDepartNo, curDepart, CPUID, PrBarcode = "";
    EditText edt_barcode,edt_checkReal;
    Button btn_find,btn_Query,btn_Select,btn_MarkBadPoint;
    ImageButton btn_editBarcode;
    ListView measureListView;
    TextView txt_HintInfo,txt_OrderNo,txt_StyleNo,txt_PO,txt_Color,txt_Size,txt_StyleSort,txt_Depart,txt_PSXX;
    TextView txt_checkItem;
    String  selDepartNo="",selDepart="",selOrderNo="",selStyleNo="",selPO="",selColor="",selSize="",selStyleSort="",selImageFile="",selPSXX="",selManuDepartNo="";
    Button view_oneBtn, view_twoBtn, view_threeBtn, view_fourBtn, view_fiveBtn, view_sixBtn, view_sevenBtn, view_eightBtn, view_nineBtn, view_zeroBtn, view_delBtn, view_pointBtn;
    Button view_clearBtn,view_submitBtn,view_affirmBtn,view_IncNum,view_DecNum;
    TextView txt_QuestionCodes, txt_QCNumber;
    //其他变量
    JSONArray resultJSON,partJson, measureJSON,questionJson;
    SQLiteDatabase tmpdb;
    private ProgressDialog waitDialog = null;
    MeasureListAdapter measureListAdapter;
    int curProcPosition = -1;
    int curMeasurePostion = -1;
    boolean firstLoad=true;
    View tmpItemView;
    private FragmentG.FragmentGCallBack mFragmentGCallBack;

    public interface FragmentGCallBack {
        // 里面传个值@param Map<String,Object>适应多种类型;
        void FragmentGWorkAndTransParams(Map<String, Object> Params);
    }

    //判断是否为数字，不然不转
    public static boolean isNumeric(String str) {
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Activity activity = (Activity) context;
        if (!(activity instanceof FragmentG.FragmentGCallBack)) {
            throw new IllegalStateException("MainActivity必须实现FragmentGCallBack接口");
        }
        mFragmentGCallBack=(FragmentG.FragmentGCallBack) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mFragmentGCallBack=null;

    }

    public FragmentG() {
        // Required empty public constructor
    }

    //消息回调
    public void ToSpeech(String paramText){
        //传消息给主界面;
        if (mFragmentGCallBack!=null)
        {
            fragmentParams.clear();
            fragmentParams.put("ParamComm","Speech");//命令;
            fragmentParams.put("Text",paramText);//命令;
            mFragmentGCallBack.FragmentGWorkAndTransParams(fragmentParams);
        } else Log.d("msg","mFragmentGCallBack-----------空的咋办");
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        measureListAdapter=new MeasureListAdapter(getContext());
        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity = (MainActivity) getActivity();
        mainHandler = activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerG(new MainActivity.OnTransParamsListenerG() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams != null) {
                    try {
                        String paramComm = mParams.get("ParamComm").toString();
                        if (paramComm == "LoginParam") {
                            Log.d(this.getClass().getName(), "LoginParam------------------>1");
                            //传递登陆参数信息;
                            curLoginUserNo = mParams.get("LoginUserNo").toString();
                            curLoginUser = mParams.get("LoginUser").toString();
                            curServiceUrl = mParams.get("ServiceUrl").toString();
                            curServiceDir= mParams.get("ServiceDir").toString();
                            curDepartNo = mParams.get("DepartNo").toString();
                            curDepart = mParams.get("Depart").toString();
                            CPUID = mParams.get("CPUID").toString();
                            Log.d(this.getClass().getName(), "LoginParam------------------>2");
                            //发消息置焦点
                            Message msg = new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                        }
                        if (paramComm=="BlueParam") {
                            System.out.println(mParams);
                            //14mm初始值
                            int lenght=Integer.parseInt(mParams.get("lenght").toString())+14;
                            int power=Integer.parseInt(mParams.get("power").toString());
                            if (curMeasurePostion >-1){
                                if (lenght<0) lenght=0;
                                edt_checkReal.setText(String.format("%.1f",((float)lenght/10)));
                                view_affirmBtn.performClick();
                            }
                        }
                        if ((paramComm=="Barcode")){
                            String barcode=mParams.get("Barcode").toString();
                            edt_barcode.setText(barcode);
                            scanBarcodeData(barcode);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }


    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg != null) {
                //消息处理;
                System.out.println("收到的消息是："+msg.what);
                int msgId = msg.what;
                switch (msgId) {
                    case msgFocusBarcode:
                        setEditBarcodeFocus();
                        break;
                    case MSG_SCANBARCODE:
                        fillFormtext();
                        setEditBarcodeFocus();
                        break;
                    case MSG_SUBMIT:
                        fillFormtext();
                        break;
                    case MSG_MEASURE:
                        measureListView.setAdapter(measureListAdapter);
                        break;
                    case MSG_FocusDefaultItem:
                        if ((measureListAdapter.getCount()>0)&&(firstLoad)){
                            firstLoad=false;
                            //measureListView.requestFocusFromTouch();
                            measureListView.setSelection(0);
                            //measureListView.requestFocus(0);
                            measureListView.getChildAt(0).setSelected(true);
                            measureListView.performItemClick(measureListView.getChildAt(0), 0, measureListView.getItemIdAtPosition(0));
                        }
                        break;
                    case msgGetImg:
                        getImage(selImageFile, selOrderNo, selStyleNo, selStyleSort);
                        break;

                    default:
                        break;
                }
            }
        }
    };

    //获取图片;
    private void getImage(final String paramImageFile,final String paramOrderNo,final String paramStyleNo,final String paramStyleSort)
    {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    ResultSet re = DBUtil.OpenSQL("Exec KeyPoint_GetStyleImg @OrderNo='"+paramOrderNo+"',@StyleNo='" + paramStyleNo + "',@StyleSort='" + paramStyleSort + "'");
                    if (re != null) {
                        re.next();
                        //使用Blob对象接收数据库里的图片
                        if (re.findColumn("ImgResult") > -1) {
                            String ImgResult = re.getString("ImgResult");
                            if (ImgResult.equals("OK")) {
                                java.sql.Blob imgBlob = re.getBlob("ImgFile");
                                //获取Blob对象的二进制流;
                                InputStream imgInS = imgBlob.getBinaryStream();
                                //加载一个网络图片
                                Bitmap bitmap = BitmapFactory.decodeStream(imgInS);
                                //保存图片;
                                saveBitmap(bitmap, paramImageFile);
                            }
                        }
                    }
                    re.getStatement().getConnection().close();
                } catch (SQLException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(run).start();
    }

    /**
     * 保存文件
     */
    public void saveBitmap(Bitmap bm, String fileName) {
        //获取MainActivity
        MainActivity activity = (MainActivity) getActivity();
        //String imgfilepath=activity.SaveFilePath+activity.SaveIMGFolder;
        String imgfilepath = activity.getCacheDir().toString();
        Log.d("saveBitmap", "imgfilepath:" + imgfilepath);
        File f = new File(imgfilepath, fileName);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            if (fileName.toUpperCase().indexOf("PNG") > 0)
                bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            if ((fileName.toUpperCase().indexOf("JPG") > 0) || (fileName.toUpperCase().indexOf("JPEG") > 0))
                bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            Log.i("saveBitmap", fileName+"已经保存成功");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_g, container, false);
        initView(root);
        System.out.println(this.getClass().getName() + "_onCreateView");
        return root;
    }

    private void initView(View view) {
        btn_MarkBadPoint=view.findViewById(R.id.btn_MarkBadPoint);
        btn_MarkBadPoint.setOnClickListener(this);
        btn_find=view.findViewById(R.id.btn_find);
        btn_find.setOnClickListener(this);
        btn_Query=view.findViewById(R.id.btn_Query);
        btn_Query.setOnClickListener(this);
        btn_Select=view.findViewById(R.id.btn_Select);
        btn_Select.setOnClickListener(this);
        measureListView=view.findViewById(R.id.measureListView);
        measureListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                view.setSelected(true);
                try {
                    txt_checkItem.setText(measureJSON.optJSONObject(i).getString("PartName"));
                    ToSpeech("测量"+txt_checkItem.getText().toString());
                    edt_checkReal.setText("");
                    curMeasurePostion=i;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        txt_checkItem=view.findViewById(R.id.txt_checkItem);
        btn_editBarcode=(ImageButton)view.findViewById(R.id.btn_editBarcode);
        btn_editBarcode.setOnClickListener(this);
        btn_editBarcode.setFocusable(false);
        btn_editBarcode.setFocusableInTouchMode(false);
        edt_checkReal=view.findViewById(R.id.edt_checkReal);
        //界面Edit;
        edt_barcode=(EditText)view.findViewById(R.id.edt_barcode);
        edt_barcode.setInputType(InputType.TYPE_NULL);
        edt_barcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    if ((event.getAction()==KeyEvent.ACTION_DOWN)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        playRingtone();
                        hideIM(v);
                        if (edt_barcode.getText().length()==0) {
                            curToast.setText(getString(R.string.PleaseInputBarcode));
                            curToast.show();
                        }
                        //未有焦点
                        scanBarcodeData(edt_barcode.getText().toString());
                        //发消息置焦点
                        Message msg =new Message();
                        msg.what = msgFocusBarcode;
                        fragmentHandler.removeMessages(msg.what);
                        fragmentHandler.sendMessage(msg);
                    }

                }
                return false;
            }
        });
        edt_barcode.requestFocus();
        edt_barcode.requestFocusFromTouch();
        txt_HintInfo=view.findViewById(R.id.txt_HintInfo);
        txt_OrderNo=view.findViewById(R.id.txt_OrderNo);
        txt_StyleNo=view.findViewById(R.id.txt_StyleNo);
        txt_PO=view.findViewById(R.id.txt_PO);
        txt_Color=view.findViewById(R.id.txt_Color);
        txt_Size=view.findViewById(R.id.txt_Size);
        txt_StyleSort=view.findViewById(R.id.txt_StyleSort);
        txt_PSXX=view.findViewById(R.id.txt_PSXX);
        txt_Depart=view.findViewById(R.id.txt_Depart);
        //按键
        view_oneBtn = view.findViewById(R.id.view_oneBtn);
        view_oneBtn.setOnClickListener(this);
        view_twoBtn = view.findViewById(R.id.view_twoBtn);
        view_twoBtn.setOnClickListener(this);
        view_threeBtn = view.findViewById(R.id.view_threeBtn);
        view_threeBtn.setOnClickListener(this);
        view_fourBtn =  view.findViewById(R.id.view_fourBtn);
        view_fourBtn.setOnClickListener(this);
        view_fiveBtn =  view.findViewById(R.id.view_fiveBtn);
        view_fiveBtn.setOnClickListener(this);
        view_sixBtn =  view.findViewById(R.id.view_sixBtn);
        view_sixBtn.setOnClickListener(this);
        view_sevenBtn = view.findViewById(R.id.view_sevenBtn);
        view_sevenBtn.setOnClickListener(this);
        view_eightBtn =  view.findViewById(R.id.view_eightBtn);
        view_eightBtn.setOnClickListener(this);
        view_nineBtn =  view.findViewById(R.id.view_nineBtn);
        view_nineBtn.setOnClickListener(this);
        view_zeroBtn = view.findViewById(R.id.view_zeroBtn);
        view_zeroBtn.setOnClickListener(this);
        view_delBtn =  view.findViewById(R.id.view_delBtn);
        view_delBtn.setOnClickListener(this);
        view_pointBtn = view.findViewById(R.id.view_pointBtn);
        view_pointBtn.setOnClickListener(this);
        view_clearBtn = view.findViewById(R.id.view_clearBtn);
        view_clearBtn.setOnClickListener(this);
        view_submitBtn= view.findViewById(R.id.view_submitBtn);
        view_submitBtn.setOnClickListener(this);
        view_affirmBtn=view.findViewById(R.id.view_affirmBtn);
        view_affirmBtn.setOnClickListener(this);
        //疵点代码
        txt_QuestionCodes=view.findViewById(R.id.txt_QuestionCodes);
        txt_QuestionCodes.setOnClickListener(this);
        txt_QCNumber =view.findViewById(R.id.txt_QCNumber);
        view_IncNum=view.findViewById(R.id.view_IncNum);
        view_IncNum.setOnClickListener(this);
        view_DecNum=view.findViewById(R.id.view_DecNum);
        view_DecNum.setOnClickListener(this);

        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);
    }


    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getActivity().getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(getActivity(), notification);
        r.play();

    }

    //根据卡号或条码刷新数据;
    private void scanBarcodeData(String BarcodeParam) {
        playRingtone();
        PrBarcode = BarcodeParam;
        try {
            resultJSON = new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_MeasureScan @Barcode='" + BarcodeParam + "',@OPERTYPE='SCANBARCODE',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }


    //根据条码及界面上显示的内容调用尺寸数据;
    private void GetMeasure( String OrderNoParam, String StyleNoParam,String StyleSortParam,String SizeParam) {
        try {
            measureJSON = new JSONArray("[]");
            tmpItemView=null;
            firstLoad=true;
            curMeasurePostion = -1;
            measureListAdapter.notifyDataSetChanged();
            measureListView.setAdapter(measureListAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_MeasureGetSize @OrderNo='" + OrderNoParam + "',@StyleNo='" + StyleNoParam + "',@StyleSort='" + StyleSortParam+ "',@Size='" + SizeParam
                + "',@OPERTYPE='MEASURE',@UserNo='" + curLoginUserNo + "',@CPUID='" + CPUID + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }


    //清除界面显示内容
    private void clearFormText() {
        /*

         */
    }

    //填充界面显示内容;
    private void fillFormtext(){
        if (resultJSON.length()>0)
        {
            try {
                if (resultJSON.getJSONObject(0).has("QCCode")){
                    String QCCode=resultJSON.getJSONObject(0).getString("QCCode");
                    if (QCCode.length()==0) txt_QuestionCodes.setText("");
                    else {
                        String tmpQuestion = txt_QuestionCodes.getText().toString();
                        if (tmpQuestion.length() > 0) {
                            if (tmpQuestion.indexOf(QCCode) == -1)
                                tmpQuestion = tmpQuestion + ',' + QCCode;
                        } else tmpQuestion = QCCode;
                        txt_QuestionCodes.setText(tmpQuestion);
                    }
                }
                if (resultJSON.getJSONObject(0).has("QCNumber")){
                    String QCNumber=resultJSON.getJSONObject(0).getString("QCNumber");
                    txt_QCNumber.setText(QCNumber);
                }
                //别的参数刷新
                if (resultJSON.getJSONObject(0).has("OrderNo")==true) {
                    selOrderNo=resultJSON.getJSONObject(0).getString("OrderNo");
                    txt_OrderNo.setText(selOrderNo);
                }
                if (resultJSON.getJSONObject(0).has("StyleNo")==true){
                    selStyleNo=resultJSON.getJSONObject(0).getString("StyleNo");
                    txt_StyleNo.setText(selStyleNo);
                }
                if (resultJSON.getJSONObject(0).has("StyleSort")==true){
                    selStyleSort=resultJSON.getJSONObject(0).getString("StyleSort");
                    txt_StyleSort.setText(selStyleSort);
                }
                if (resultJSON.getJSONObject(0).has("Depart")==true){
                    selDepart=resultJSON.getJSONObject(0).getString("Depart");
                    txt_Depart.setText(selDepart);
                }
                if (resultJSON.getJSONObject(0).has("DepartNo")==true){
                    selDepartNo=resultJSON.getJSONObject(0).getString("DepartNo");
                }
                if (resultJSON.getJSONObject(0).has("ManuDepartNo")==true){
                    selManuDepartNo=resultJSON.getJSONObject(0).getString("ManuDepartNo");
                }

                if (resultJSON.getJSONObject(0).has("PO")==true) {
                    selPO=resultJSON.getJSONObject(0).getString("PO");
                    txt_PO.setText(selPO);
                }
                if (resultJSON.getJSONObject(0).has("Color")==true) {
                    selColor=resultJSON.getJSONObject(0).getString("Color");
                    txt_Color.setText(selColor);

                }
                if (resultJSON.getJSONObject(0).has("Size")==true) {
                    selSize=resultJSON.getJSONObject(0).getString("Size");
                    txt_Size.setText(selSize);
                }
                if (resultJSON.getJSONObject(0).has("PSXX")==true) {
                    selPSXX=resultJSON.getJSONObject(0).getString("PSXX");
                    txt_PSXX.setText(selPSXX);
                }
                if (resultJSON.getJSONObject(0).has("ImageFile")==true) {
                    selImageFile=resultJSON.getJSONObject(0).getString("ImageFile");
                    if (selImageFile.length()>0) GetStyleInfo(selImageFile);
                }
                if (resultJSON.getJSONObject(0).has("ClearData")==true) {
                    if (resultJSON.getJSONObject(0).getString("ClearData").equals("YES")) ClearData();
                }
                if (resultJSON.getJSONObject(0).has("LoadDetail")==true) {
                    if (resultJSON.getJSONObject(0).getString("LoadDetail").equals("YES")) GetMeasure(selOrderNo,selStyleNo,selStyleSort,selSize);
                }
                if (resultJSON.getJSONObject(0).has("HintInfo")==true) txt_HintInfo.setText(resultJSON.getJSONObject(0).getString("HintInfo"));
                if (resultJSON.getJSONObject(0).has("ErrInfo")==true)
                {
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle("系统提示").setMessage(resultJSON.getJSONObject(0).getString("ErrInfo"))
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    hideBottomUIMenu();
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


    }

    private void ClearData() {
        if (measureJSON!=null){
            firstLoad=true;
            for (int i=0;i<measureJSON.length();i++){
                try {
                    measureJSON.optJSONObject(i).put("RealMeasure","");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            measureListAdapter.notifyDataSetChanged();
        }
    }

    //获取填写的行数
    private int GetFillCount() {
        int rstCount=0;
        if (measureJSON!=null){
            for (int i=0;i<measureJSON.length();i++){
                try {
                    String RealMeasure=measureJSON.optJSONObject(i).getString("RealMeasure");
                    if ((RealMeasure!=null)&&(RealMeasure.length()>0)) rstCount++;
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return  rstCount;
    }

    //跳转到下一个
    private void goToDimensItem(int curIndex){
        if (curIndex<0){
            curIndex=0;
        }
        try {
            if (measureJSON==null) return;
            if (curIndex<measureJSON.length()) {
                curMeasurePostion =curIndex;
                if ((measureListAdapter.getCount()>curMeasurePostion)){
                    //measureListView.requestFocusFromTouch();
                    measureListView.setSelection(curIndex);
                    //measureListView.requestFocus(curIndex);
                    measureListView.performItemClick(measureListView.getChildAt(curIndex), curIndex, measureListView.getItemIdAtPosition(curIndex));
                }
            } else{
                //语音播报已测量完成;
                ToSpeech("已测量完成");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = getActivity().getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }

    //设置焦点到扫描输入框
    private void setEditBarcodeFocus() {
        //设置焦点
        System.out.println(TAG+" 设置焦点-------------------------------1.Start");
        if (edt_barcode != null) {
            edt_barcode.selectAll();
            edt_barcode.setFocusable(true);
            edt_barcode.setFocusableInTouchMode(true);
            edt_barcode.requestFocus();
            edt_barcode.requestFocusFromTouch();
            hideIM(getView());
            hideBottomUIMenu();
        }
        System.out.println(TAG+" 设置焦点-------------------------------1.End");
    }

    @Override
    public void onStart() {
        super.onStart();
        setEditBarcodeFocus();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("requestCode:"+requestCode+" resultCode:"+resultCode);
        //选合约返回
        if ((requestCode==1000)&&(resultCode==1001)){
            //获取登陆参数
            Bundle paramBundle = data.getExtras();
            selDepart=paramBundle.getString("selDepart");
            selDepartNo=paramBundle.getString("selDepartNo");
            selOrderNo=paramBundle.getString("selOrderNo");
            selStyleNo=paramBundle.getString("selStyleNo");
            selStyleSort=paramBundle.getString("selStyleSort");
            selPO=paramBundle.getString("selPO");
            selColor=paramBundle.getString("selColor");
            selSize=paramBundle.getString("selSize");
            selPSXX=paramBundle.getString("selPSXX");
            selManuDepartNo=paramBundle.getString("selManuDepartNo");
            selImageFile=paramBundle.getString("selImageFile");
            //填充界面
            txt_OrderNo.setText(selOrderNo);
            txt_StyleNo.setText(selStyleNo);
            txt_StyleSort.setText(selStyleSort);
            txt_PO.setText(selPO);
            txt_Size.setText(selSize);
            txt_Color.setText(selColor);
            txt_Depart.setText(selDepart);
            txt_PSXX.setText(selPSXX);
            if (selImageFile.length()>0) GetStyleInfo(selImageFile);
            GetMeasure(selOrderNo,selStyleNo,selStyleSort,selSize);
            getPart(selOrderNo,selStyleNo,selStyleSort);
        }

        //选疵点返回
        if ((requestCode==2000)&&(resultCode==2001)){
            //获取登陆参数
            Bundle paramBundle = data.getExtras();
            try {
                questionJson= new JSONArray(paramBundle.getString("questionJson"));
                if (questionJson.length()>0){
                    txt_QuestionCodes.setText(questionJson.optJSONObject(0).getString("QuestionCodes"));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        hideBottomUIMenu();
    }


    //获取部位数据
    private void getPart(String selOrderNo, String selStyleNo, String selStyleSort) {
        String SqlComm="Exec KeyPoint_RepairGetPart @OrderNo='" + selOrderNo + "',@StyleNo='" + selStyleNo+ "',@StyleSort='" + selStyleSort
                + "',@OPERTYPE='GetPart',@UserNo='"+curLoginUserNo+ "',@CPUID='"+CPUID+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }


    //获取图形及部位数据
    private void GetStyleInfo(String paramImageFile) {
        String imgfilepath = getActivity().getCacheDir().toString();
        File file = new File(imgfilepath + "/" + paramImageFile);
        System.out.println("图片文件路径:" + imgfilepath + "/" + paramImageFile);
        //判断图片是否存在，如果不存在则从网络获取;
        if (file.exists() == true) {
            Log.d(TAG, "本地有取图片---------------");
            //从本地取图片
            //Bitmap bitmap = getLoacalBitmap(imgfilepath + "/" + curImageFileName);
            //imageLayout.setImgBg(bitmap);
        } else {
            Log.d(TAG, "发消息从网络获取图片---------------");
            //Drawable drawable = getResources().getDrawable(R.mipmap.err404);
            //BitmapDrawable errBitDraw = (BitmapDrawable) drawable;
            //imageLayout.setImgBg(errBitDraw.getBitmap());
            //发前消息，获取图片;
            Message msg = new Message();
            msg.what = msgGetImg;
            fragmentHandler.removeMessages(msg.what);
            fragmentHandler.sendMessage(msg);
        }
    }


    @Override
    public void onClick(View v) {
        hideIM(v);
        hideBottomUIMenu();
        switch (v.getId()) {
            case R.id.txt_QuestionCodes:
                txt_QuestionCodes.setText("");
                break;
            case R.id.btn_MarkBadPoint:
                MakeBadPoint("Single");
                break;
            case R.id.btn_find:
                if (edt_barcode.getText().length()>0){
                    scanBarcodeData(edt_barcode.getText().toString());
                } else {
                    curToast.setText("请先输入条码!");
                    curToast.show();
                    return;
                }
                break;
            case R.id.btn_Query:
                Intent intentQueryActivity=new Intent(getContext(),QueryActivity.class);
                Bundle paramBundle = new Bundle();
                paramBundle.clear();
                paramBundle.putString("LoginUserNo", curLoginUserNo);
                paramBundle.putString("LoginUser",curLoginUser);
                paramBundle.putString("CurDepartNo",curDepartNo);
                paramBundle.putString("CurDepart",curDepart);
                paramBundle.putString("ServiceUrl",curServiceUrl);
                paramBundle.putString("ServiceDir",curServiceDir);
                paramBundle.putString("CPUID",CPUID);
                paramBundle.putString("QueryTitle", "成衣尺寸查询");
                paramBundle.putString("OrderNo",txt_OrderNo.getText().toString());
                paramBundle.putString("StyleNo",txt_StyleNo.getText().toString());
                paramBundle.putString("StyleSort",txt_StyleSort.getText().toString());
                paramBundle.putString("NeedOrder","YES");
                intentQueryActivity.putExtras(paramBundle);
                startActivity(intentQueryActivity);
                break;
            case R.id.btn_Select:
                Intent intentStyleNoActivity=new Intent(getContext(),StyleNoActivity.class);
                Bundle paramBundle2 = new Bundle();
                paramBundle2.clear();
                paramBundle2.putString("LoginUserNo", curLoginUserNo);
                paramBundle2.putString("LoginUser",curLoginUser);
                paramBundle2.putString("CurDepartNo",curDepartNo);
                paramBundle2.putString("CurDepart",curDepart);
                paramBundle2.putString("ServiceUrl",curServiceUrl);
                paramBundle2.putString("ServiceDir",curServiceDir);
                if (selDepart.length()==0) {
                    selDepart=curDepart;
                    selDepartNo=curDepartNo;
                }
                paramBundle2.putString("selDepart",selDepart);
                paramBundle2.putString("selDepartNo",selDepartNo);
                paramBundle2.putString("FormType","REPAIR");
                paramBundle2.putInt("DateNum",10);
                paramBundle2.putString("CPUID",CPUID);
                intentStyleNoActivity.putExtras(paramBundle2);
                startActivityForResult(intentStyleNoActivity,1000);
                break;
            case R.id.btn_editBarcode:
                edt_barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edt_barcode,InputMethodManager.SHOW_FORCED);
                break;

            case R.id.view_oneBtn:
            case R.id.view_twoBtn:
            case R.id.view_threeBtn:
            case R.id.view_fourBtn:
            case R.id.view_fiveBtn:
            case R.id.view_sixBtn:
            case R.id.view_sevenBtn:
            case R.id.view_eightBtn:
            case R.id.view_nineBtn:
            case R.id.view_zeroBtn:
                Button tmpBtn1 = v.findViewById(v.getId());
                edt_checkReal.getText().append(tmpBtn1.getText());
                break;
            case R.id.view_delBtn:
                if (edt_checkReal.getText().length() > 0) {
                    edt_checkReal.setSelection(edt_checkReal.getText().length());
                    int start = edt_checkReal.getSelectionStart();
                    edt_checkReal.getText().delete(start - 1, start);
                }
                break;
            case R.id.view_pointBtn:
                System.out.println("AindexOf:" + edt_checkReal.getText().toString().indexOf("."));
                if ((edt_checkReal.getText().toString().indexOf(".") == -1)&&(edt_checkReal.getText().toString().indexOf("/") == -1)) {
                    edt_checkReal.getText().append(".");
                }
                break;
            case R.id.view_clearBtn:
                edt_checkReal.setText("");
                break;
            case R.id.view_affirmBtn:
                if ((edt_checkReal.getText().length() > 0)&&(curMeasurePostion>-1)&&(measureJSON!=null)){
                    try {
                        //判断值是否超过公差;
                        String MinValue = measureJSON.optJSONObject(curMeasurePostion).getString("MinValue");
                        String MaxValue = measureJSON.optJSONObject(curMeasurePostion).getString("MaxValue");
                        String ConColor= CheckMeasureDiffer(edt_checkReal.getText().toString(),MaxValue, MinValue);
                        measureJSON.optJSONObject(curMeasurePostion).put("ConColor", ConColor);
                        measureJSON.optJSONObject(curMeasurePostion).put("RealMeasure", edt_checkReal.getText().toString());
                        //更新修改过的行;
                        measureListAdapter.notifyDataSetChanged();
                        goToDimensItem(curMeasurePostion+1);
                        //只更新修改过的值;
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    curToast.setText("请输入实际尺寸！");
                    curToast.show();
                }
                break;
            case R.id.view_submitBtn:
                putMeasureList( txt_OrderNo.getText().toString(), txt_StyleNo.getText().toString(),txt_StyleSort.getText().toString());
                break;

            case R.id.view_IncNum:
                txt_QCNumber.setText(String.valueOf(IncQCNumber(1)));
                break;
            case R.id.view_DecNum:
                txt_QCNumber.setText(String.valueOf(IncQCNumber(-1)));
                break;
            default:
                break;
        }

    }

    //坏点记录根据类型显示不同界面
    private void MakeBadPoint(String paramClipType){
        if ((selDepartNo.length()==0)||(selStyleNo.length()==0)){
            curToast.setText("请先选择合约!");
            curToast.show();
            return;
        }
        Intent intentQuestionActivity=new Intent(getContext(),QuestionActivity.class);
        Bundle paramBundle1 = new Bundle();
        paramBundle1.clear();
        paramBundle1.putString("LoginUserNo", curLoginUserNo);
        paramBundle1.putString("LoginUser",curLoginUser);
        paramBundle1.putString("CurDepartNo",curDepartNo);
        paramBundle1.putString("CurDepart",curDepart);
        paramBundle1.putString("ServiceUrl",curServiceUrl);
        paramBundle1.putString("ServiceDir",curServiceDir);
        if (selDepart.length()==0) {
            selDepart=curDepart;
            selDepartNo=curDepartNo;
        }
        paramBundle1.putString("selDepart",selDepart);
        paramBundle1.putString("selDepartNo",selDepartNo);
        paramBundle1.putString("selImageFile",selImageFile);
        paramBundle1.putString("selStyleNo",selStyleNo);
        paramBundle1.putString("selOrderNo",selOrderNo);
        paramBundle1.putString("selStyleSort",selStyleSort);
        paramBundle1.putString("ClipType",paramClipType);
        paramBundle1.putString("TitleInv","疵点选择");
        paramBundle1.putString("NeedPos","NO");//图片标注
        paramBundle1.putInt("MaxPieces",1);
        paramBundle1.putString("CPUID",CPUID);
        intentQuestionActivity.putExtras(paramBundle1);
        startActivityForResult(intentQuestionActivity,2000);
    }
    //订单表格适配器;
    public final class MeasureListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private int defItem;
        public MeasureListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return measureJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return measureJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void setDefSelect(int position) {
            this.defItem = position;
            notifyDataSetChanged();
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder=new ViewHolder();
                //可以理解为从vlist获取view 之后把view返回给ListView
                convertView =inflater.inflate(R.layout.fragment_g_checkitem, null, false);
                holder.btn_DecNum = convertView.findViewById(R.id.btn_DecNum);
                holder.btn_IncNum = convertView.findViewById(R.id.btn_IncNum);
                convertView.setTag(holder);
            }else {
                holder = (ViewHolder)convertView.getTag();
            }
            holder.btn_DecNum.setTag(position);
            holder.btn_DecNum.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    transCheckValue(position,(float)-0.1);
                }
            });
            holder.btn_IncNum.setTag(position);
            holder.btn_IncNum.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    transCheckValue(position,(float)0.1);
                }
            });
            try {
                Log.d("msg","getView()----------------------------------------------------->"+position);
                String ConColor="0";
                String tmpStr="";
                Integer textColor=getResources().getColor(R.color.text_black);
                if (measureJSON.optJSONObject(position).has("ConColor")){
                    if (measureJSON.optJSONObject(position).getString("ConColor").equals("1")) textColor=getResources().getColor(R.color.green);
                    if (measureJSON.optJSONObject(position).getString("ConColor").equals("2")) textColor=getResources().getColor(R.color.red);
                }
                TextView tv = convertView.findViewById(R.id.item_PartName);// 显示文字
                if (measureJSON.optJSONObject(position).has("PartName") == true)
                    tv.setText(measureJSON.optJSONObject(position).get("PartName").toString());
                tv = convertView.findViewById(R.id.item_Measure);// 显示文字
                if (measureJSON.optJSONObject(position).has("Measure") == true)
                    tv.setText(measureJSON.optJSONObject(position).get("Measure").toString());
                tv.setTextColor(getResources().getColor(R.color.text_blue));
                tv = convertView.findViewById(R.id.item_CommDiffer);// 显示文字
                if (measureJSON.optJSONObject(position).has("CommDiffer") == true)
                    tmpStr=measureJSON.optJSONObject(position).get("CommDiffer").toString();
                    System.out.println(tmpStr.indexOf(","));
                    if (tmpStr.indexOf(",")>0)  tv.setText(tmpStr.substring(0,tmpStr.indexOf(","))+"\n"+tmpStr.substring(tmpStr.indexOf(",")+1));
                    else tv.setText(tmpStr);
                tv = convertView.findViewById(R.id.item_RealMeasure);// 显示文字
                if (measureJSON.optJSONObject(position).has("RealMeasure") == true)
                    tv.setText(measureJSON.optJSONObject(position).get("RealMeasure").toString());
                tv.setTextColor(textColor);
                //默认选中第0个，因为还没有确定界面，所以要延时选中;
                if (position==measureJSON.length()-1) {
                    Log.d("msg","tmpItemView.postDelayed");
                    tmpItemView=convertView;
                    //刷新界面;
                    Message msg = new Message();
                    msg.what = MSG_FocusDefaultItem;
                    fragmentHandler.removeMessages(msg.what);
                    fragmentHandler.sendMessage(msg);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            Log.d("msg","MeasureListAdapter_position:"+position);
            return convertView;
        }

        public void transCheckValue(int position,float paramValue){
            try {
                String RealMeasure=measureJSON.optJSONObject(position).getString("RealMeasure");
                String Measure=measureJSON.optJSONObject(position).getString("Measure");
                String MaxValue=measureJSON.optJSONObject(position).getString("MaxValue");
                String MinValue=measureJSON.optJSONObject(position).getString("MinValue");
                if (RealMeasure.length()==0) RealMeasure=Measure;
                Float tmpValue=Float.valueOf(RealMeasure)+paramValue;
                DecimalFormat  df= new DecimalFormat("######0.00");
                if (tmpValue>0) measureJSON.optJSONObject(position).put("RealMeasure",df.format(tmpValue));
                String ConColor=CheckMeasureDiffer(df.format(tmpValue),MaxValue,MinValue);
                measureJSON.optJSONObject(position).put("ConColor",ConColor);
                measureListAdapter.notifyDataSetChanged();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        //提取出来方便点
        public final class ViewHolder {
            public Button btn_IncNum;
            public Button btn_DecNum;
        }
    }

    //用于检查值是否超出范围
    private String CheckMeasureDiffer(String paramRealMeasure, String paramMaxMeasure, String paramMinMeasure) {
        String ConColor;
        ConColor = "0";
        DecimalFormat  df= new DecimalFormat("######0.00");
        System.out.println("paramRealMeasure"+paramRealMeasure+" paramMaxMeasure:"+paramMaxMeasure+" paramMinMeasure:"+paramMinMeasure);
        if ((isNumeric(paramRealMeasure) == true) && (isNumeric(paramMaxMeasure) == true)&& (isNumeric(paramMinMeasure) == true)) {
            float Real=Float.valueOf(df.format(Float.parseFloat(paramRealMeasure)));
            float Max=Float.valueOf(df.format(Float.parseFloat(paramMaxMeasure)));
            float Min=Float.valueOf(df.format(Float.parseFloat(paramMinMeasure)));
            if ( Real>Max||Real<Min)
                ConColor = "2";
            else ConColor = "1";
        }
        return ConColor;
    }

    //QC件数变化
    public int IncQCNumber(int paramValue){
        int tmpValue=0;
        try {
            String QCNumber=txt_QCNumber.getText().toString();
            if (QCNumber.length()==0) QCNumber="0";
            tmpValue=Integer.parseInt(QCNumber)+paramValue;
            if (tmpValue==0)tmpValue=0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tmpValue;
    }

    //提交所选择的工序至服务器,然后刷新工序列表;
    private void putMeasureList(final String paramOrderNo,final String paramStyleNo,final String paramStyleSort) {
        if (measureJSON == null) return;
        if (GetFillCount()==0) {
            curToast.setText("尚未填写尺寸，暂无法提交!");
            curToast.show();
            return;
        }
        if ((txt_QCNumber.getText().toString().length()==0)||Integer.parseInt(txt_QCNumber.getText().toString())==0){
            curToast.setText("请输入件数，暂无法提交!");
            curToast.show();
            return;
        }
        Runnable run = new Runnable() {
            @Override
            public void run() {
                String SqlComm;
                String tmpMeasureID = java.util.UUID.randomUUID().toString();
                //将数据读到JSONArray;
                try {
                    PreparedStatement pstmt = DBUtil.getSQLConnection().prepareStatement(
                            "Insert into KeyPointMeasureDe(MeasureDeID,MeasureMaID,PartName,Measure,CommDiffer,RealMeasure,DifferValue) values(newid(),?,?,?,?,?,?)");
                    //增加明细表
                    for (int i = 0; i < measureJSON.length(); i++) {
                        if (measureJSON.getJSONObject(i).has("RealMeasure") == true) {
                            if (measureJSON.getJSONObject(i).getString("RealMeasure").length() > 0) {
                                pstmt.setString(1, tmpMeasureID);
                                pstmt.setString(2, measureJSON.getJSONObject(i).getString("PartName"));
                                pstmt.setString(3, measureJSON.getJSONObject(i).getString("Measure"));
                                pstmt.setString(4, measureJSON.getJSONObject(i).getString("CommDiffer"));
                                pstmt.setString(5, measureJSON.getJSONObject(i).getString("RealMeasure"));
                                pstmt.setString(6, measureJSON.getJSONObject(i).getString("DifferValue"));
                                pstmt.executeUpdate();
                            }
                        }
                    }
                    pstmt.close();
                    //增加主表;
                    pstmt = DBUtil.getSQLConnection().prepareStatement(
                            "Insert into KeyPointMeasureMa(MeasureMaID,Barcode,OrderNo,StyleNO,StyleSort,PO,Color,PSXX,Size,UserNo,UserName,CPUID,QCCodes,QCNumber,CreateTime,DepartNo,ManuDepartNo) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,getdate(),?,?)");
                    pstmt.setString(1, tmpMeasureID);
                    pstmt.setString(2, PrBarcode);
                    pstmt.setString(3, paramOrderNo);
                    pstmt.setString(4, paramStyleNo);
                    pstmt.setString(5, paramStyleSort);
                    pstmt.setString(6, selPO);
                    pstmt.setString(7, selColor);
                    pstmt.setString(8, selPSXX);
                    pstmt.setString(9, selSize);
                    pstmt.setString(10, curLoginUserNo);
                    pstmt.setString(11, curLoginUser);
                    pstmt.setString(12, CPUID);
                    pstmt.setString(13, txt_QuestionCodes.getText().toString());
                    pstmt.setString(14, txt_QCNumber.getText().toString());
                    pstmt.setString(15, selDepartNo);
                    pstmt.setString(16, selManuDepartNo);
                    pstmt.executeUpdate();
                    pstmt.close();
                    //调用存储过程;
                    SqlComm = " Exec KeyPoint_MeasureSaveTrans @MeasureMaID='" + tmpMeasureID + "'";
                    ReadSQLData(SqlComm);
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        };
        new Thread(run).start();
    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public synchronized void run() {
                try{
                    reentrantLock.lock();
                    JSONArray jsonArray  = DBUtil.QuerySQL2JSON(SQLComm);
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("OPERTYPE") == true) {
                            System.out.println("OPERTYPE:" + jsonArray.optJSONObject(0).getString("OPERTYPE"));
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("SCANBARCODE")) {
                                resultJSON = jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_SCANBARCODE;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                            //获取尺寸数据
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("MEASURE")) {
                                System.out.println("获取到成衣尺寸数据");
                                measureJSON = jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_MEASURE;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);

                            }
                            //获取尺寸数据
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").equals("SUBMIT")) {
                                System.out.println("提交处理完成");
                                resultJSON = jsonArray;
                                //刷新界面;
                                Message msg = new Message();
                                msg.what = MSG_SUBMIT;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);

                            }
                            if (jsonArray.optJSONObject(0).getString("OPERTYPE").toUpperCase().equals("GETPART")){
                                partJson=jsonArray;
                                //将数据放到Part表中
                                if (tmpdb==null) OpenCreateDB();
                                try {
                                    tmpdb.execSQL("Delete from PartDefine");
                                    for (int i=0;i<partJson.length();i++) {
                                        tmpdb.execSQL("Insert into PartDefine(PartName,PosX,PosY) values(?,?,?)",
                                                new Object[]{partJson.optJSONObject(i).getString("PartName"),
                                                        partJson.optJSONObject(i).getLong("PosX"),
                                                        partJson.optJSONObject(i).getLong("PosY"),
                                                });
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                    curToast.setText("部位定义数据暂存完成:\r\b"+e.getMessage());
                                    curToast.show();
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    reentrantLock.unlock();
                }finally {
                    reentrantLock.unlock();
                }

            }

        };
        new Thread(run).start();
    }


    //打开数据库
    public void OpenCreateDB(){
        if (tmpdb==null) {
            MainActivity activity = (MainActivity) getActivity();
            tmpdb = activity.mainDB;
        }
    }



}